package apiserver

import (
	"cs0512/fmr/internal/apiserver/config"
	"cs0512/fmr/internal/apiserver/options"
	"cs0512/fmr/pkg/app"

	"github.com/marmotedu/log"
)

const commandDesc = "家庭病历本系统"

func NewApp(basename string) *app.App {
	opts := options.NewOptions()
	application := app.NewApp("FMR",
		basename,
		app.WithOptions(opts),
		app.WithDescription(commandDesc),
		app.WithRunFunc(run(opts)),
	)

	return application
}

func run(opts *options.Options) app.RunFunc {
	return func(basename string) error {
		log.Init(opts.Log)
		defer log.Flush()

		cfg, err := config.CreateConfigFromOptions(opts)
		if err != nil {
			return err
		}

		return Run(cfg)
	}
}

// Run runs the specified APIServer. This should never exit.
func Run(cfg *config.Config) error {
	server, err := createAPIServer(cfg)
	if err != nil {
		return err
	}
	return server.PrepareRun().Run()
}
